package android.tusnotas.core;

import android.tusnotas.beans.Ack;
import android.tusnotas.connector.webservice.WebServiceCaller;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.parser.push.AckParser;
import android.tusnotas.util.Devel;
import android.util.Log;

public class PushAckAnalyser {

	private WebServiceCaller caller = new WebServiceCaller();

	private int ttt = 5;//times to try before giving up connection try

	public Ack doGetPushAck(String appId, String androidId) throws RemoteReadingException, ProcessingInstancesException{
		String XML = doGetPushAckXml(appId, androidId);
		Ack ack = doObtainPushAck(XML);
		
		return ack;
	}

	private Ack doObtainPushAck(String XML) throws ProcessingInstancesException{
		Ack ack = null;

		AckParser ackParser = new AckParser();
		try {
			ack = ackParser.parseXML(XML);
		} catch (Exception e) {
			e.printStackTrace();
			Log.w(getClass().getName(),"Can't read push ack status");
		}
		return ack;
	}

	private String doGetPushAckXml(String appId, String androidId) throws RemoteReadingException{
		String XML="";
		try {
			caller.setAckPush(appId, androidId);
			XML = persistentCaller();
		} catch (Exception e) {
			if( Devel.fullDevel){
				Log.w(this.getClass().getName(), "No notifications were found");
			}
			RemoteReadingException rwce = new RemoteReadingException();
			rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
			throw rwce;
		}
		return XML;
	}

	private String persistentCaller() throws RemoteReadingException{	
		while( ttt > 0){
			try{
				String XML = caller.execute();
				return XML;
			}catch(RemoteReadingException e){}
			ttt--;
		}
		throw new RemoteReadingException();
	}

//	public List<TusNotasNotification> getBarNotifications(ListaNotificaciones lista, Context context){
//
//		TusNotasModel tnm = TusNotasModel.getTusNotasModel(context);
//
//		List<TusNotasNotification> result = new ArrayList<TusNotasNotification>();
//
//		for(int i=0; i<lista.getNotifications().size(); i++){
//			PushNotification n = lista.getNotifications().get(i);
//			Course c = tnm.selectCourseByIdAula(new Integer(n.getIdAula()));
//			TusNotasNotification notification = new NewPushNotification(new PushChange(context,n,c));
//			result.add(notification);
//		}
//		return result;
//	}
	
}
